package cn.ug.product.web.job;

import cn.ug.config.RedisGlobalLock;
import cn.ug.feign.GoldPriceNowApiService;
import cn.ug.feign.GoldPriceService;
import cn.ug.feign.LondonGoldService;
import cn.ug.feign.UGoldPriceService;
import cn.ug.product.bean.GoldPriceBaselineBean;
import cn.ug.product.bean.GoldPriceRecordBean;
import cn.ug.product.bean.GoldPriceResponseNowApiBean;
import cn.ug.product.service.GoldPriceBaselineService;
import cn.ug.product.service.GoldPriceRecordService;
import cn.ug.util.BigDecimalUtil;
import cn.ug.util.GoldPriceJCTYUtil;
import cn.ug.util.UF;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

/**
 * 金价查询定时任务
 * @author kaiwotech
 */
@Component
public class GoldPriceJobs {
    private Log log = LogFactory.getLog(GoldPriceJobs.class);
    /** 业务有效期 */
    private static final long EXPIRE_DAY = 1;

    @Resource
    private GoldPriceService goldPriceService;
    @Resource
    private GoldPriceNowApiService goldPriceNowApiService;
    @Resource
    private GoldPriceRecordService goldPriceRecordService;
    @Resource
    private GoldPriceBaselineService goldPriceBaselineService;
    @Autowired
    private LondonGoldService londonGoldService;
    @Autowired
    private UGoldPriceService uGoldPriceService;
    @Resource
    private RedisGlobalLock redisGlobalLock;
    @Value("${juhe.finance.gold.shgold.key}")
    private String appKey;
    @Autowired
    public ObjectMapper objectMapper;
    @Value("${spring.cloud.config.profile}")
    private String profile;


    /**
     * 金价查询，每十分钟触发一次
     */
     @Scheduled(fixedRate = 60 * 1000)
    public void juheLatestGoldPriceJob() {
        if (StringUtils.equals(profile, "dev")) {
            return;
        }
       /* String key = "GoldPriceJobs:juheLatestGoldPriceJob:" + UF.getFormatDateTime("yyyy-MM-ddHH:mm", UF.getDateTime());
        key = key + (UF.getDateTime().getSecond() / 60);
        if(!redisGlobalLock.lock(key, EXPIRE_DAY, TimeUnit.HOURS)) {
            // 如果没有获取到锁
            return;
        }*/
        String result = uGoldPriceService.query();
        if (StringUtils.isNotBlank(result)) {
            JSONObject data = JSONObject.parseObject(result);
            if (data != null && StringUtils.isNotBlank(data.getString("data"))) {
                List<GoldPriceRecordBean> records = JSONObject.parseArray(data.getString("data"), GoldPriceRecordBean.class);
                if (records != null && records.size() > 0) {
                    for (GoldPriceRecordBean record : records) {
                        goldPriceRecordService.save(record);
                        try {
                            Thread.sleep(19000);
                        } catch (Exception e) {

                        }
                    }
                }
            }
        }
        /*String key = "GoldPriceJobs:juheLatestGoldPriceJob:" + UF.getFormatDateTime("yyyy-MM-ddHH:mm", UF.getDateTime());
        // 锁定20秒的倍数
        key = key + (UF.getDateTime().getSecond() / 20);
        if(!redisGlobalLock.lock(key, EXPIRE_DAY, TimeUnit.HOURS)) {
            // 如果没有获取到锁
            return;
        }
       // log.info("juhe 金价查询接口调用 =====================================");
       // log.info(UF.getFormatDateTime(UF.getDateTime()));
       // log.info("appKey = " + appKey);

        String jsonText = goldPriceService.query(appKey);
       // log.info("聚合实时金价查询结果：" + jsonText);
        try {
            GoldPriceResponseBean o = objectMapper.readValue(jsonText, GoldPriceResponseBean.class);
            if(null == o) {
                return;
            }
            String resultcode = o.getResultcode();
            if(StringUtils.isBlank(resultcode) || !resultcode.equals("200")) {
                log.error("金价接口出错：reason = " + o.getReason());
                return;
            }

            GoldPriceBaselineBean goldPriceBaselineBean = goldPriceBaselineService.findLastByTime();

            String goldType = "3"; // Au(T+D)
            Map<String, Map<String, String>> mapMap = o.getResult().get(0);
            Map<String, String> dataMap = mapMap.get(goldType);

            // 品种
            String variety = dataMap.get("variety");
            // 最新价
            String latestpri = dataMap.get("latestpri");
            // 开盘价
            String openpri = dataMap.get("openpri");
            // 最高价
            String maxpri = dataMap.get("maxpri");
            // 最低价
            String minpri = dataMap.get("minpri");
            // 涨跌幅（%）
            String limit = dataMap.get("limit");
            // 昨收价
            String yespri = dataMap.get("yespri");
            // 总成交量
            String totalvol = dataMap.get("totalvol");
            // 更新时间
            String time = dataMap.get("time");

            String none = "--";
            GoldPriceRecordBean goldPriceRecordBean = new GoldPriceRecordBean();
            goldPriceRecordBean.setType(1);
            goldPriceRecordBean.setActualpri(new BigDecimal(latestpri));
            goldPriceRecordBean.setVariety(variety);

            if(none.equals(latestpri)) {
                log.info("金价为--：latestpri = " + latestpri);
                return;
            }
            *//*if (none.equals(latestpri)) {
                log.info("金价为--：yespri = " + latestpri);
                return;
            }*//*
            // 最新金价相关开始 ###################################################################
            goldPriceRecordBean.setLatestpri(new BigDecimal(latestpri));
            // TODO 金价上浮0.2元
            goldPriceRecordBean.setLatestpri(BigDecimalUtil.add(goldPriceRecordBean.getLatestpri(), new BigDecimal("0.20")));
            // TODO 金价加随机数
            goldPriceRecordBean.setLatestpri(BigDecimalUtil.add(goldPriceRecordBean.getLatestpri(), new BigDecimal(getValue())));
            // 和基准金价比较，防止异常金价
            if(null != goldPriceBaselineBean &&
                    !BigDecimalUtil.isZeroOrNull(goldPriceBaselineBean.getMaxPrice()) &&
                    !BigDecimalUtil.isZeroOrNull(goldPriceBaselineBean.getMinPrice()) &&
                    !BigDecimalUtil.isZeroOrNull(goldPriceRecordBean.getLatestpri())) {
                if(goldPriceRecordBean.getLatestpri().compareTo(goldPriceBaselineBean.getMaxPrice()) > 0) {
                    // 大于上限
                    goldPriceRecordBean.setLatestpri(goldPriceBaselineBean.getMaxPrice());
                }
                if(goldPriceRecordBean.getLatestpri().compareTo(goldPriceBaselineBean.getMinPrice()) < 0) {
                    // 小于下限
                    goldPriceRecordBean.setLatestpri(goldPriceBaselineBean.getMinPrice());
                }
            }
            // 最新金价相关结束 ###################################################################

            if(!none.equals(openpri)) {
                goldPriceRecordBean.setOpenpri(new BigDecimal(openpri));
            }
            if(!none.equals(maxpri)) {
                goldPriceRecordBean.setMaxpri(new BigDecimal(maxpri));
            }
            if(!none.equals(minpri)) {
                goldPriceRecordBean.setMinpri(new BigDecimal(minpri));
            }
            if(!none.equals(limit)) {
                limit = limit.replace("%", "");
                goldPriceRecordBean.setLimit(new BigDecimal(limit));
            }
            if(!none.equals(yespri)) {
                goldPriceRecordBean.setYespri(new BigDecimal(yespri));
            }
            if(!none.equals(totalvol)) {
                goldPriceRecordBean.setTotalvol(new BigDecimal(totalvol));
            }
            goldPriceRecordBean.setTimeString(time);
            goldPriceRecordBean.setDescription("juhe");

            goldPriceRecordService.save(goldPriceRecordBean);
        } catch (IOException e) {
            log.error("解析金价接口发生异常", e);
        }*/
    }

    /**
     * 金价查询，40秒触发一次
     */
    @Scheduled(fixedRate = 20 * 1000)
    public void nowapiLatestGoldPriceJob() {
        if (!StringUtils.equals(profile, "dev")) {
            return;
        }
        String key = "GoldPriceJobs:nowapiLatestGoldPriceJob:" + UF.getFormatDateTime("yyyy-MM-ddHH:mm", UF.getDateTime());
        // 锁定20秒的倍数
        key = key + (UF.getDateTime().getSecond() / 20);
        if(!redisGlobalLock.lock(key, EXPIRE_DAY, TimeUnit.HOURS)) {
            // 如果没有获取到锁
            return;
        }
//        appKey = "http://api.k780.com/?app=finance.shgold&goldid=1051&version=2&appkey=33074&sign=d854fdb856dcc92492a70295c5a387de&format=json";
        // goldid	string	否	编号可包含 1051:黄金T+D,1052:白银T+D,1053:黄金9999,1054:黄金9995,1055:白银9999,1056:铂金9995,1057:白银999,1058:金条100g,1059:黄金T+N1,1060:黄金T+N2
        //log.info("nowapi 金价查询接口调用 =====================================");
        //log.info(UF.getFormatDateTime(UF.getDateTime()));
//        log.info("appKey = " + appKey);

        String jsonText = goldPriceNowApiService.query();
        log.info("nowapi实时金价查询结果："+jsonText);
        try {
            GoldPriceResponseNowApiBean o = objectMapper.readValue(jsonText, GoldPriceResponseNowApiBean.class);
            if(null == o) {
                return;
            }
            String success = o.getSuccess();
            if(StringUtils.isBlank(success) || "0".equals(success)) {
                log.error("金价接口出错：jsonText = " + jsonText);
                return;
            }

//            "goldid":"1051",
//            "variety": "Ag(T+D)", /*品种*/
//            "varietynm": "白银(T+D)", /*品种名称*/
//            "last_price": "3553.00", /*当前价*/
//            "buy_price": "264.6200", /*买入价*/
//            "sell_price": "287.4000", /*卖出价*/
//            "volume": "1", /*成交量*/
//            "change_price": "0.69", /*涨跌额*/
//            "change_margin": "0.24%", /*涨跌幅*/
//            "high_price": "3588.00", /*最高价*/
//            "low_price": "3530.00", /*最低价*/
//            "open_price": "3549.00", /*开盘价*/
//            "yesy_price": "3552.00", /*昨收价*/
//            "uptime": "2015-05-11 11:12:39" /*更新时间 (行情有变化uptime才会更新)*/

            Map<String, String> dataMap = o.getResult();

            // 品种
            String variety = dataMap.get("variety");
            // 最新价
            String latestpri = dataMap.get("last_price");
            // 开盘价
            String openpri = dataMap.get("open_price");
            // 最高价
            String maxpri = dataMap.get("high_price");
            // 最低价
            String minpri = dataMap.get("low_price");
            // 涨跌幅（%）
            String limit = dataMap.get("change_margin");
            // 昨收价
            String yespri = dataMap.get("yesy_price");
            // 总成交量
            String totalvol = dataMap.get("volume");
            // 更新时间
            String time = dataMap.get("uptime");

            String none = "--";
            GoldPriceRecordBean goldPriceRecordBean = new GoldPriceRecordBean();
            goldPriceRecordBean.setType(1);
            goldPriceRecordBean.setActualpri(new BigDecimal(latestpri));
            goldPriceRecordBean.setVariety(variety);

            if(none.equals(latestpri)) {
                log.info("金价为--：latestpri = " + latestpri);
                return;
            }
            /*if (none.equals(latestpri)) {
                log.info("金价为--：yespri = " + latestpri);
                return;
            }*/
            // 最新金价相关开始 ###################################################################
            goldPriceRecordBean.setLatestpri(new BigDecimal(latestpri));
            // TODO 金价上浮0.2元
            goldPriceRecordBean.setLatestpri(BigDecimalUtil.add(goldPriceRecordBean.getLatestpri(), new BigDecimal("0.20")));
            // TODO 金价加随机数
            goldPriceRecordBean.setLatestpri(BigDecimalUtil.add(goldPriceRecordBean.getLatestpri(), new BigDecimal(getValue())));

            // 和基准金价比较，防止异常金价
            GoldPriceBaselineBean goldPriceBaselineBean = goldPriceBaselineService.findLastByTime();
            if(null != goldPriceBaselineBean &&
                    !BigDecimalUtil.isZeroOrNull(goldPriceBaselineBean.getMaxPrice()) &&
                    !BigDecimalUtil.isZeroOrNull(goldPriceBaselineBean.getMinPrice()) &&
                    !BigDecimalUtil.isZeroOrNull(goldPriceRecordBean.getLatestpri())) {
                if(goldPriceRecordBean.getLatestpri().compareTo(goldPriceBaselineBean.getMaxPrice()) > 0) {
                    // 大于上限
                    goldPriceRecordBean.setLatestpri(goldPriceBaselineBean.getMaxPrice());
                }
                if(goldPriceRecordBean.getLatestpri().compareTo(goldPriceBaselineBean.getMinPrice()) < 0) {
                    // 小于下限
                    goldPriceRecordBean.setLatestpri(goldPriceBaselineBean.getMinPrice());
                }
            }
            // 最新金价相关结束 ###################################################################

            if(!none.equals(openpri)) {
                goldPriceRecordBean.setOpenpri(new BigDecimal(openpri));
            }
            if(!none.equals(maxpri)) {
                goldPriceRecordBean.setMaxpri(new BigDecimal(maxpri));
            }
            if(!none.equals(minpri)) {
                goldPriceRecordBean.setMinpri(new BigDecimal(minpri));
            }
            if(!none.equals(limit)) {
                limit = limit.replace("%", "");
                goldPriceRecordBean.setLimit(new BigDecimal(limit));
            }
            if(!none.equals(yespri)) {
                goldPriceRecordBean.setYespri(new BigDecimal(yespri));
            }
            if(!none.equals(totalvol)) {
                goldPriceRecordBean.setTotalvol(new BigDecimal(totalvol));
            }
            goldPriceRecordBean.setTimeString(time);
            goldPriceRecordBean.setDescription("nowapi");

            goldPriceRecordService.save(goldPriceRecordBean);
        } catch (IOException e) {
            log.error("解析金价接口发生异常", e);
        }
    }

    /**
     * 伦敦金价40秒触发一次
     */
    //@Scheduled(fixedRate = 40 * 1000)
    public void londonLatestGoldPriceJob() {
        String key = "GoldPriceJobs:londonLatestGoldPriceJob:" + UF.getFormatDateTime("yyyy-MM-ddHH:mm", UF.getDateTime());
        // 锁定20秒的倍数
        key = key + (UF.getDateTime().getSecond() / 40);
        if(!redisGlobalLock.lock(key, EXPIRE_DAY, TimeUnit.HOURS)) {
            // 如果没有获取到锁
            return;
        }
//        appKey = "http://api.k780.com/?app=finance.shgold&goldid=1051&version=2&appkey=33074&sign=d854fdb856dcc92492a70295c5a387de&format=json";
        // goldid	string	否	编号可包含 1051:黄金T+D,1052:白银T+D,1053:黄金9999,1054:黄金9995,1055:白银9999,1056:铂金9995,1057:白银999,1058:金条100g,1059:黄金T+N1,1060:黄金T+N2
        // log.info("london 金价查询接口调用 =====================================");
        //log.info(UF.getFormatDateTime(UF.getDateTime()));
//        log.info("appKey = " + appKey);

        String jsonText = londonGoldService.query();
        // log.info("london实时金价查询结果："+jsonText);
        try {
            GoldPriceResponseNowApiBean o = objectMapper.readValue(jsonText, GoldPriceResponseNowApiBean.class);
            if(null == o) {
                return;
            }
            String success = o.getSuccess();
            if(StringUtils.isBlank(success) || "0".equals(success)) {
                log.error("金价接口出错：jsonText = " + jsonText);
                return;
            }

//            "goldid":"1051",
//            "variety": "Ag(T+D)", /*品种*/
//            "varietynm": "白银(T+D)", /*品种名称*/
//            "last_price": "3553.00", /*当前价*/
//            "buy_price": "264.6200", /*买入价*/
//            "sell_price": "287.4000", /*卖出价*/
//            "volume": "1", /*成交量*/
//            "change_price": "0.69", /*涨跌额*/
//            "change_margin": "0.24%", /*涨跌幅*/
//            "high_price": "3588.00", /*最高价*/
//            "low_price": "3530.00", /*最低价*/
//            "open_price": "3549.00", /*开盘价*/
//            "yesy_price": "3552.00", /*昨收价*/
//            "uptime": "2015-05-11 11:12:39" /*更新时间 (行情有变化uptime才会更新)*/

            Map<String, String> dataMap = o.getResult();

            // 品种
            String variety = dataMap.get("variety");
            // 最新价
            String latestpri = dataMap.get("last_price");
            // 开盘价
            String openpri = dataMap.get("open_price");
            // 最高价
            String maxpri = dataMap.get("high_price");
            // 最低价
            String minpri = dataMap.get("low_price");
            // 涨跌幅（%）
            String limit = dataMap.get("change_margin");
            // 昨收价
            String yespri = dataMap.get("yesy_price");
            // 总成交量
            String totalvol = dataMap.get("volume");
            // 更新时间
            String time = dataMap.get("uptime");

            String none = "--";
            GoldPriceRecordBean goldPriceRecordBean = new GoldPriceRecordBean();
            goldPriceRecordBean.setType(1);
            goldPriceRecordBean.setActualpri(new BigDecimal(latestpri));
            goldPriceRecordBean.setVariety(variety);

            if(none.equals(latestpri)) {
                log.info("金价为--：latestpri = " + latestpri);
                return;
            }
            // 最新金价相关开始 ###################################################################
            goldPriceRecordBean.setLatestpri(new BigDecimal(latestpri));
            // TODO 金价上浮0.2元
            goldPriceRecordBean.setLatestpri(BigDecimalUtil.add(goldPriceRecordBean.getLatestpri(), new BigDecimal("0.20")));
            // TODO 金价加随机数
            goldPriceRecordBean.setLatestpri(BigDecimalUtil.add(goldPriceRecordBean.getLatestpri(), new BigDecimal(getValue())));

            // 和基准金价比较，防止异常金价
            GoldPriceBaselineBean goldPriceBaselineBean = goldPriceBaselineService.findLastByTime();
            if(null != goldPriceBaselineBean &&
                    !BigDecimalUtil.isZeroOrNull(goldPriceBaselineBean.getMaxPrice()) &&
                    !BigDecimalUtil.isZeroOrNull(goldPriceBaselineBean.getMinPrice()) &&
                    !BigDecimalUtil.isZeroOrNull(goldPriceRecordBean.getLatestpri())) {
                if(goldPriceRecordBean.getLatestpri().compareTo(goldPriceBaselineBean.getMaxPrice()) > 0) {
                    // 大于上限
                    goldPriceRecordBean.setLatestpri(goldPriceBaselineBean.getMaxPrice());
                }
                if(goldPriceRecordBean.getLatestpri().compareTo(goldPriceBaselineBean.getMinPrice()) < 0) {
                    // 小于下限
                    goldPriceRecordBean.setLatestpri(goldPriceBaselineBean.getMinPrice());
                }
            }
            // 最新金价相关结束 ###################################################################

            if(!none.equals(openpri)) {
                goldPriceRecordBean.setOpenpri(new BigDecimal(openpri));
            }
            if(!none.equals(maxpri)) {
                goldPriceRecordBean.setMaxpri(new BigDecimal(maxpri));
            }
            if(!none.equals(minpri)) {
                goldPriceRecordBean.setMinpri(new BigDecimal(minpri));
            }
            if(!none.equals(limit)) {
                limit = limit.replace("%", "");
                goldPriceRecordBean.setLimit(new BigDecimal(limit));
            }
            if(!none.equals(yespri)) {
                goldPriceRecordBean.setYespri(new BigDecimal(yespri));
            }
            if(!none.equals(totalvol)) {
                if (StringUtils.isBlank(totalvol)) {
                    totalvol = String.valueOf(0);
                }
                goldPriceRecordBean.setTotalvol(new BigDecimal(totalvol));
            }
            goldPriceRecordBean.setTimeString(time);
            goldPriceRecordBean.setDescription("london");

            goldPriceRecordService.save(goldPriceRecordBean);
        } catch (IOException e) {
            log.error("解析金价接口发生异常", e);
        }
    }
    /**
     * 金价查询，二十秒触发一次
     */
    //@Scheduled(fixedRate = 20 * 1000)
    public void jctyLatestGoldPriceJob() {
        String key = "GoldPriceJobs:jctyLatestGoldPriceJob:" + UF.getFormatDateTime("yyyy-MM-ddHH:mm", UF.getDateTime());
        // 锁定20秒的倍数
        key = key + (UF.getDateTime().getSecond() / 20);
        if(!redisGlobalLock.lock(key, EXPIRE_DAY, TimeUnit.HOURS)) {
            // 如果没有获取到锁
            return;
        }
        // log.info("jcty 金价查询接口调用 =====================================");
        // log.info(UF.getFormatDateTime(UF.getDateTime()));
//        log.info("appKey = " + appKey);

        try {
            String jsonText = GoldPriceJCTYUtil.query();
            System.out.println(jsonText);

            List<LinkedHashMap<String, Object>> dataList = objectMapper.readValue(jsonText, List.class);
            if(null == dataList || dataList.isEmpty()) {
                log.error("金价接口出错：jsonText = " + jsonText);
                return;
            }

            /*String success = o.getSuccess();
            if(StringUtils.isBlank(success) || "0".equals(success)) {
                log.error("金价接口出错：jsonText = " + jsonText);
                return;
            }*/

//            "goldid":"1051",
//            "variety": "Ag(T+D)", /*品种*/
//            "varietynm": "白银(T+D)", /*品种名称*/
//            "last_price": "3553.00", /*当前价*/
//            "buy_price": "264.6200", /*买入价*/
//            "sell_price": "287.4000", /*卖出价*/
//            "volume": "1", /*成交量*/
//            "change_price": "0.69", /*涨跌额*/
//            "change_margin": "0.24%", /*涨跌幅*/
//            "high_price": "3588.00", /*最高价*/
//            "low_price": "3530.00", /*最低价*/
//            "open_price": "3549.00", /*开盘价*/
//            "yesy_price": "3552.00", /*昨收价*/
//            "uptime": "2015-05-11 11:12:39" /*更新时间 (行情有变化uptime才会更新)*/

            LinkedHashMap<String, Object> dataMap = null;
            for (LinkedHashMap<String, Object> map : dataList) {
                if(null == map || map.isEmpty()) {
                    continue;
                }
                String symbol = map.get("Symbol").toString();
                if(!StringUtils.equals("SGAuT+D", symbol)) {
                    continue;
                }
                dataMap = map;
            }
            if(null == dataMap || dataMap.isEmpty()) {
                log.error("金价解析出错：dataMap = " + dataMap);
                return;
            }

            // 品种
            String variety = dataMap.get("Name").toString();
            // 最新价
            String latestpri = dataMap.get("NewPrice").toString();
            // 开盘价
            String openpri = dataMap.get("Open").toString();
            // 最高价
            String maxpri = dataMap.get("High").toString();
            // 最低价
            String minpri = dataMap.get("Low").toString();
            // 涨跌幅（%）
            String limit = dataMap.get("PriceChangeRatio").toString();
            // 昨收价
            String yespri = dataMap.get("LastClose").toString();
            // 总成交量
            String totalvol = dataMap.get("Volume").toString();
            // 更新时间
            String time = dataMap.get("Date").toString();

            // 秒时间戳转毫秒时间戳
            time += "000";
            time = UF.getFormatDateTime(LocalDateTime.ofInstant(new Date(Long.valueOf(time)).toInstant(), ZoneId.of("UTC+08:00")));

            String none = "--";
            GoldPriceRecordBean goldPriceRecordBean = new GoldPriceRecordBean();
            goldPriceRecordBean.setType(1);
            goldPriceRecordBean.setActualpri(new BigDecimal(latestpri));
            goldPriceRecordBean.setVariety(variety);

            if(none.equals(latestpri)) {
                log.info("金价为--：latestpri = " + latestpri);
                return;
            }
            // 最新金价相关开始 ###################################################################
            goldPriceRecordBean.setLatestpri(new BigDecimal(latestpri));
            // TODO 金价上浮0.2元
            goldPriceRecordBean.setLatestpri(BigDecimalUtil.add(goldPriceRecordBean.getLatestpri(), new BigDecimal("0.20")));
            // TODO 金价加随机数
            goldPriceRecordBean.setLatestpri(BigDecimalUtil.add(goldPriceRecordBean.getLatestpri(), new BigDecimal(getValue())));

            // 和基准金价比较，防止异常金价
            GoldPriceBaselineBean goldPriceBaselineBean = goldPriceBaselineService.findLastByTime();
            if(null != goldPriceBaselineBean &&
                    !BigDecimalUtil.isZeroOrNull(goldPriceBaselineBean.getMaxPrice()) &&
                    !BigDecimalUtil.isZeroOrNull(goldPriceBaselineBean.getMinPrice()) &&
                    !BigDecimalUtil.isZeroOrNull(goldPriceRecordBean.getLatestpri())) {
                if(goldPriceRecordBean.getLatestpri().compareTo(goldPriceBaselineBean.getMaxPrice()) > 0) {
                    // 大于上限
                    goldPriceRecordBean.setLatestpri(goldPriceBaselineBean.getMaxPrice());
                }
                if(goldPriceRecordBean.getLatestpri().compareTo(goldPriceBaselineBean.getMinPrice()) < 0) {
                    // 小于下限
                    goldPriceRecordBean.setLatestpri(goldPriceBaselineBean.getMinPrice());
                }
            }
            // 最新金价相关结束 ###################################################################

            if(!none.equals(openpri)) {
                goldPriceRecordBean.setOpenpri(new BigDecimal(openpri));
            }
            if(!none.equals(maxpri)) {
                goldPriceRecordBean.setMaxpri(new BigDecimal(maxpri));
            }
            if(!none.equals(minpri)) {
                goldPriceRecordBean.setMinpri(new BigDecimal(minpri));
            }
            if(!none.equals(limit)) {
                limit = limit.replace("%", "");
                goldPriceRecordBean.setLimit(new BigDecimal(limit));
            }
            if(!none.equals(yespri)) {
                goldPriceRecordBean.setYespri(new BigDecimal(yespri));
            }
            if(!none.equals(totalvol)) {
                goldPriceRecordBean.setTotalvol(new BigDecimal(totalvol));
            }
            goldPriceRecordBean.setTimeString(time);
            goldPriceRecordBean.setDescription("jcty");

            goldPriceRecordService.save(goldPriceRecordBean);
        } catch (IOException e) {
            log.error("解析金价接口发生异常", e);
        }
    }

    private double getValue() {
        Calendar cal = Calendar.getInstance();
        int week = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (week < 0) {
            week = 0;
        }
        ThreadLocalRandom random = ThreadLocalRandom.current();
        Double[] infos = {-0.02, -0.01, 0.0, 0.01, 0.02};
        SimpleDateFormat timeFormat = new SimpleDateFormat("HHmm");
        int point = Integer.parseInt(timeFormat.format(new Date()));
        double value = 0;
        switch (week) {
            case 0:
                value = 0;
                break;
            case 1:
                if ((point >= 0 && point <= 900)
                        || (point >= 1130 && point <= 1330)
                        || (point >= 1530 && point <= 2000)) {
                    value = 0;
                } else {
                    value = infos[random.nextInt(0, 5)];
                }
                break;
            case 2:
            case 3:
            case 4:
            case 5:
                if ((point >= 230 && point <= 900)
                        || (point >= 1130 && point <= 1330)
                        || (point >= 1530 && point <= 2000)) {
                    value = 0;
                } else {
                    value = infos[random.nextInt(0, 5)];
                }
                break;
            case 6:
                if (point >= 230 && point <= 2359) {
                    value = 0;
                } else {
                    value = infos[random.nextInt(0, 5)];
                }
                break;
            default:
                value = 0;
        }
        return value;
    }
}
